<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta charset="utf-8">
  <meta name="viewport"
    content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
  <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
  <link href="bg.css?v=5" rel="stylesheet" />
  <link href="aui.css" rel="stylesheet" />
  <style>
    body {
      padding: 0px;
      margin: 0px;
      overflow: hidden;
    }

    #cas {
      display: block;
      border: 1px solid;
      margin: auto;
      background-color: #000
    }

    .showBg {
      background-color: transparent !important;
    }

    .showSomething {
      position: fixed;
      left: 20px;
      top: 20px;
    }

    .game {
      width: 100%;
      margin: auto;
      height: 100%;
      position: relative;
    }


    #point {
      width: 100%;
      height: 50px;
      position: absolute;
      top: 0px;
      color: #FFF;
      font: 20px "微软雅黑";
      display: none;
    }

    #gameScore {
      background-color: black;
      opacity: 0.5;
      width: 90%;
      height: 60%;
      position: absolute;
      top: 20px;
      left: 0px;
      right: 0px;
      margin: 0 auto;
      display: none;
      border: solid 2px white;
      border-radius: 5px;
      overflow: hidden;
    }

    #gameScore ol {
      width: 95%;
      height: 100%;
      overflow: scroll;
      margin: 0 auto;
    }

    #gameScore ol li {
      padding-top: 5px;
      padding-bottom: 5px;
      width: 100%;
      color: aqua;
      font-size: 0.8rem;
      overflow: hidden;
    }

    #gameScore ol li span {
      width: 33%;
      text-align: left;
      font-size: 0.8rem;
      overflow: hidden;
    }

    #gameStart {
      position: absolute;
      width: 100%;
      text-align: center;
      bottom: 10px;
      display: none;
    }

    #gameStart #gs-start {
      display: inline-block;
      width: 180px;
      height: 40px;
      background-color: aqua;
      color: #000;
      line-height: 30px;
      border-radius: 10px;
      border: 5px solid #FFF;
    }

    #gameStart #gs-start:hover {
      color: #f00;
    }

    #god {
      position: absolute;
      display: block;
      right: -150px;
      top: 100px;
      width: 140px;
      text-align: center
    }

    #verygod {
      position: absolute;
      display: block;
      right: -150px;
      top: 150px;
      width: 140px;
      text-align: center
    }

    #pretygod {
      position: absolute;
      display: block;
      right: -150px;
      top: 200px;
      width: 140px;
      text-align: center
    }

    #nogod {
      position: absolute;
      display: block;
      right: -150px;
      top: 250px;
      width: 140px;
      text-align: center
    }
  </style>
  <title>飞机游戏</title>
</head>

<body>
  <div class="game">
    <div id="gameStart">
      <span id="gs-start">病毒狙击战开始</span>
      <img src='../../images/logo.png' style="width:40px;height:40px;margin:10px auto;" />
    </div>
    <div id="gameScore">
      <h3 style="width: 100%;text-align:center;color:white;font-weight:bold;padding-top:5px;padding-bottom:5px;">抗疫排行榜
      </h3>
      <ol id="scoreRank" start="1" type="1"></ol>
    </div>
    <div id="bg0">
    </div>
    <canvas id='cas' width="700" height="750">您的浏览器不支持canvas，请更新浏览器</canvas>

  </div>
  <script src="js/api.js"></script>
  <script src="js/business.js"></script>
  <script src="js/data.js?v=3"></script>
  <!-- <script src="js/loading.js?v=10"></script> -->
  <!-- <script src="js/allSprite.js?v=4"></script> -->
  <script>
    

    var canvas = document.getElementById("cas");
    var ctx = canvas.getContext('2d');
    var systemType;
    var img = new Image(),
      gameScore = document.getElementById("gameScore"),
      gS = document.getElementById("gameStart"),
      gss = document.getElementById("gs-start");

    var sprites = [],
      missles = [],
      booms = [],
      foods = [],
      badPlanNum = 30,
      point = 0,
      myplan = null,
      foodDate = null,
      lifeNum = 5;
    businessNames.rank = {
      method: "get",
      url: "act=member_game&op=rank&rows={rows}&gn={gn}&key={key}"
    };
    businessNames.save_score = {
      method: "get",
      url: "act=member_game&op=save_score&gs={gs}&gn={gn}&key={key}"
    };
    document.write("<script src='js/loading.js?v=" + Math.random() + "'><\/script>");
    document.write("<script src='js/allSprite.js?v=" + Math.random() + "'><\/script>");
    
    apiready = function () {
      systemType = api.systemType;
      canvas.width = api.winWidth;
      canvas.height = api.frameHeight;

      str = "";
      for (var i = 0; i < 4; i++) {
        var tmpp = parseInt(Math.random() * 20 + 1);
        str += '<div class="slideshow-image" style="background-image: url(\'image/' + tmpp + '.jpg\')"></div>';
      }
      $api.append($api.byId('bg0'), str);
      $api.addCls($api.byId('bg0'), 'slideshow');

      window.RAF = (function () {
        return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window
          .mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
          function (callback) {
            window.setTimeout(callback, 1000 / 60);
          };
      })();
      canvas.ontouchmove = function (e) {
          e.preventDefault();
          if (e.changedTouches) {
            e = e.changedTouches[e.changedTouches.length - 1];
          }
          var x = parseInt(e.clientX);
          var y = parseInt(e.clientY);
          myplan.left = x;
          myplan.top = y - 50;
      }

      canvas.ontouchend = function (event) {
        myplan.fire = false;
      }
      canvas.ontouchstart = function (e) {
        myplan.fire = true;
      }

      $api.showFrame();
      stage.start();

    }
    
    Array.prototype.foreach = function (callback) {
      for (var i = 0; i < this.length; i++) {
        callback.apply(this[i], [i]);
      }
    }
    // 随机掉落物品的列表
    var godTimeout;
    var foodMaps = {
      LevelUP: {
        weight: 30,
        effect() {
          myplan.fireLevel = myplan.fireLevel >= 4 ? myplan.fireLevel : myplan.fireLevel + 1;
        }
      },
      SpeedUP: {

        weight: 30,
        effect() {
          myplan.firePerFrame = myplan.firePerFrame <= 10 ? 10 : myplan.firePerFrame - 10;
        }
      },
      God: {

        weight: 30,
        effect() {
          clearTimeout(godTimeout);
          myplan.god = true;
          godTimeout = setTimeout(function () {
            myplan.god = false
          }, 15000);
        }
      },
      Boom: {
        weight: 30,
        effect() {
          sprites.foreach(function () {
            var bp = this;
            if (bp.name === "badPlan" && bp.visible) {
              bp.visible = false;
              point += bp.badKind;
              boom(bp);
            }
          });
        }
      }
    };
    // 计算每种食物命中的概率
    var foodAllWeight = 0;
    var currentProb = 0;
    Object.keys(foodMaps).forEach(key => foodAllWeight += foodMaps[key].weight);
    Object.keys(foodMaps).forEach(key => {
      var probility = foodMaps[key].weight / foodAllWeight;
      foodMaps[key].start = currentProb;
      foodMaps[key].end = currentProb + probility;
      currentProb = foodMaps[key].end;
    });

    function boom(plan, my) {
      for (var j = 0; j < booms.length; j++) {
        if (!booms[j].visible) {
          booms[j].left = plan.left;
          booms[j].top = plan.top;
          booms[j].visible = true;
          if (my == undefined) my = 'boom';
          var audio = document.getElementsByTagName("audio");
          for (var i = 0; i < audio.length; i++) {
            if (audio[i].src.indexOf(my) >= 0 && (audio[i].paused || audio[i].ended)) {
              audio[i].play();
              break;
            }
          }
          break;
        }
      }
    }

    function getRank() {
      //__获取排行表
      business.getJsonDatas('rank', {
        key: '',
        gn: 'plan',
        rows: 51
      }, function (ret) {
        if (ret.success) {
          var temp = '';
          for (var i = 0; i < ret.datas.length; i++) {
            temp += '<li>' + (i + 1) + '.' + ret.datas[i].member_truename + ':' + ret.datas[i].score +
              '<span style="font-size:0.5rem;margin-left:5px;">' + ret.datas[i].u_time + '</span></li>';
          }
          $api.html($api.byId('scoreRank'), temp);

        }
      });
    }
    var stage = {
      init: function () {
        var _this = this;
        this.loading = new Loading(datas, canvas, function () {
          gS.style.display = "block";
          gameScore.style.display = "block";
          getRank();
          canvas.className = "showBg";
          gss.addEventListener("click", function () {
            gS.style.display = "none";
            gameScore.style.display = "none";
            document.getElementById("bgm").play();
            _this.addElement();

          }, false)
        });
      },
      stop: function () {
          business.getJsonDatas('save_score', {
            key: '',
            gn: 'plan',
            gs: point
          }, function (ret) {
            getRank();
          });
          api.alert({
            title: '当前回合结束',
            msg: '公元2020年注定是个不平凡的一年，别忘了我们的战斗还在继续！！'+point
          },function (ret)
          {
              sprites = [],
              missles = [],
              booms = [],
              foods = [],
              point = 0,
              myplan = null,
              foodDate = null,
              lifeNum = 5;
          });
        gS.style.display = "block";
        gameScore.style.display = "block";
        canvas.className = "showBg";

      },
      addElement: function () {
        for (var i = 0; i < 50; i++) {
          var x = Math.random() * canvas.width;
          var y = Math.random() * 2 * canvas.height - canvas.height;
          var star = new Sprite("star", starPainter, starBehavior);
          star.top = y;
          star.left = x;
          sprites.push(star);
        }

        for (var i = 0; i < badPlanNum; i++) {
          var x = Math.random() * (canvas.width - 2 * planSize().w) + planSize().w;
          var y = Math.random() * canvas.height - canvas.height;

          var badPlan = new Sprite("badPlan", badPlanPainter, badPlanBehavior);
          badPlan.top = y;
          badPlan.left = x;
          sprites.push(badPlan);
        }

        for (var i = 0; i < 400; i++) {
          var missle = new Sprite("missle", misslePainter, missleBehavior);
          missle.visible = false;
          missles.push(missle);
        }

        for (var i = 0; i < badPlanNum; i++) {
          var img = new Image();
          img.src = "image/explosion.png";
          var boom = new Sprite("boom", new SpriteSheetPainter(explosionCells, false, function () {
            this.visible = false;
          }, img));
          boom.visible = false;
          booms.push(boom);
        }

        for (var i = 0; i < 5; i++) {
          var eatfood = new Sprite("food", foodPainter, foodBehavior);
          eatfood.left = Math.random() * canvas.width - 60 + 30;
          eatfood.top = -30;
          eatfood.visible = false;
          sprites.push(eatfood);
          foods.push(eatfood);
        }

        img.src = "image/ship.png"
        myplan = new Sprite("plan", new controllSpriteSheetPainter(planCells, img), planBehavior);
        myplan.left = canvas.width / 2;
        myplan.top = canvas.height - (planSize().h / 2 + 10);
        sprites.push(myplan);
      },

      myplanReborn: function (myplan) {

        if (lifeNum <= 0) {
          stage.stop();
          return;
        }

        setTimeout(function () {
          myplan.visible = true;
          myplan.left = canvas.width / 2;
          myplan.top = canvas.height - (planSize().h / 2 + 10);
          myplan.fireLevel = 1;
          myplan.rotateAngle = 0;
          myplan.god = true;
          setTimeout(function () {
            myplan.god = false;
          }, 5000)
        }, 1000)
      },

      update: function () {
        var stage = this;
        var boomnum = 0,
          misslenum = 0;

        this.loading.loop();
        if (this.loading.getComplete()) {
          ctx.clearRect(0, 0, canvas.width, canvas.height);
        }
        missles.foreach(function () {
          var missle = this;
          sprites.foreach(function () {
            var bp = this;
            if (bp.name === "badPlan" && bp.visible && missle.visible) {
              var juli = Math.sqrt(Math.pow(missle.left - bp.left, 2) + Math.pow(missle.top - bp.top, 2));
              if (juli < (planSize().w / 2 + missle.width / 2) && missle.isgood) {
                missle.visible = false;
                bp.blood -= 50;
                if (bp.blood <= 0) {
                  bp.visible = false;
                  point += bp.badKind;
                  boom(bp)
                }
              }
            }
          });

          if (missle.visible) {
            if (!missle.isgood && myplan.visible && !myplan.god) {
              var juli = Math.sqrt(Math.pow(missle.left - myplan.left, 2) + Math.pow(missle.top - myplan.top,
                2));
              if (juli < (planSize().w / 2 + 3)) {
                myplan.visible = false;
                lifeNum--;
                missle.visible = false;
                boom(myplan, 'out')
                stage.myplanReborn(myplan)
              }
            }
            misslenum++;
            this.paint();
          }
        });

        booms.foreach(function () {
          if (this.visible) {
            boomnum++;
            this.paint();
          }
        })

        sprites.foreach(function () {
          if (this.name === "food" && this.visible) {
            var tjuli = Math.sqrt(Math.pow(this.left - myplan.left, 2) + Math.pow(this.top - myplan.top, 2));
            if (tjuli < (myplan.width / 2 + this.width / 2)) {
              this.visible = false;
              foodMaps[this.kind].effect();
            }
          }

          if (this.name === "badPlan" && myplan.visible && !myplan.god) {
            var juli = Math.sqrt(Math.pow(this.left - myplan.left, 2) + Math.pow(this.top - myplan.top, 2));
            if (juli < planSize().w) {
              myplan.visible = false;
              lifeNum--;
              this.visible = false;
              boom(this)
              boom(myplan, 'out')

              stage.myplanReborn(myplan);
            }
          }

          this.paint();
        });

        if (myplan) {
          ctx.fillStyle = "#FFF"
          ctx.font = "18px 微软雅黑";
          ctx.textAlign = "left";
          ctx.textBaseline = "middle";
          var str = "火力:" + myplan.fireLevel + ",速度:" + (80 - myplan.firePerFrame);
          ctx.fillText("得分:" + point + ",生命:" + lifeNum + '/5,' + str, 0, 18);

          if (foodDate === null) {
            foodDate = new Date();
          } else {
            var nowFoodDate = new Date();
            if (nowFoodDate - foodDate > 4000) {
              // 随机抛出食物
              var createFood = Math.random() < 0.5 ? true : false;
              var eatfood = foods.find(f => !f.visible);
              if (createFood && eatfood) {
                eatfood.left = Math.random() * canvas.width - 60 + 30;
                eatfood.top = -30;
                eatfood.visible = true;

                var random = Math.random();
                var foodList = Object.keys(foodMaps);
                for (var i = 0; i < foodList.length; i++) {
                  var food = foodMaps[foodList[i]];
                  if (random >= food.start && random <= food.end) {
                    eatfood.kind = foodList[i];
                  }
                }
              }

              foodDate = nowFoodDate;
            }
          }
        }

        //boomDom.innerHTML = "爆炸使用率(已使用/存储总量):" + boomnum + "/" + booms.length;
        //missleDom.innerHTML = "子弹使用率(已使用/存储总量):" + misslenum + "/" + missles.length;
      },

      loop: function () {
        var _this = this;
        this.update();
        RAF(function () {
          _this.loop();
        });
      },

      start: function () {
        this.init();
        this.loop();
      }
    }
  </script>
</body>

</html>